<template>
  <div class="recordDiv">
    <div v-for="(item, index) in itemList" :key="item.id">
      <div class="detailItemTop">
        <div class="detailItemTopLeft">
          {{ item[0].addtime }}
        </div>
        <div class="detailItemTopRight">
          支出: {{ item.accountSum }}
        </div>
      </div>
      <div class="detailItem" v-for="detail in item" :key="detail.budgetId" @click="getDetail(detail)">
        <div class="iconItem">
          <svg-icon :icon-file-name="detail.picture" class="detailIcon"></svg-icon>
        </div>
        <div class="nameItem"><span>{{ detail.name }}</span></div>
        <div class="amountItem"><span>{{ detail.type === "z" ? "-" : "+" }}</span><span>{{ detail.amount }}</span></div>
      </div>
      <el-divider class="divider" v-if="index < itemList.length-1"></el-divider>
    </div>

  </div>
</template>
<script>
import accountApi from "@/api/accountApi";
import router from "@/router";

export default {
  data() {
    return {
      userId: window.localStorage.getItem("userId"),
      itemList: [],
    }
  },
  props: {
    year: {
      type: String
    },
    month: {
      type: String
    }
  },
  watch: {
    'itemList': {
      handler() {
        // 遍历 items 数组，更新每个内部数组的 sum
        this.itemList.forEach(item => {
          item.accountSum = item.reduce((acc, curr) => {
            // 如果 curr.type 为 'z'（支出），则相加
            // 如果 curr.type 为 's'（收入），则相减
            return curr.type === 'z' ? acc + (+curr.amount) : acc - (+curr.amount);
          }, 0);
        });
      },
      deep: true // 深度监听，用于监听对象内部属性的变化
    }
  },

  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      const param = {
        userId: this.userId,
        year: this.year,
        month: this.month
      }
      accountApi.queryBudget(param).then(res => {
        this.itemList = res.data.data
        console.log(res.data)
      })
    },
    getDetail(item) {
      console.log(item)
      router.push("/detailUpdate")
    }
  }
}

</script>
<style scoped>
.recordDiv {
  width: 95%;
  height: calc(100% - 60px - 190px);
  overflow-y: auto;
  margin: 10px auto;
}

.detailItem {
  display: flex;
  align-items: center; /* 垂直居中 */
  margin: 10px; /* 上下左右都有10px的边距 */
}

.detailItem .iconItem {
  margin-right: 10px; /* 图标右边距 */
}

.detailItem .nameItem {
  margin-left: 15px;
  width: 70%;
  text-align: left;
}

.detailItem .amountItem {
  display: flex;
  align-items: center; /* 使金额数字垂直居中 */
  justify-content: flex-end; /* 使金额数字水平居右 */
  width: 40px;
}

.detailItemTop {
  margin-left: 5px;
  margin-right: 5px;
  font-size: 13px;
  color: #8a8a8a;
  display: flex;
  justify-content: space-between;

  .detailItemTopLeft {
    float: left;
  }

  .detailItemTopRight {
    float: right;
  }
}

.divider {
  margin: 15px 0 !important;
}


</style>